package routes;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.BeanUtilities;
import db.HibernateUtil;
import db.Routes;
import db.Users;

/**
 * Servlet implementation class Routes
 */
@WebServlet("/Routes")
public class RoutesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RoutesServlet() {
        super();

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Users user = (Users) session.getAttribute("user");
		if(user == null) {
			session.setAttribute("error", "Dostep zabrioniony");
			response.sendRedirect("/runWithJava/");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Users user = (Users) session.getAttribute("user");
		
		if(user == null) {
			session.setAttribute("error", "Dostep zabrioniony");
			response.sendRedirect("/runWithJava/");
		} else {
			Routes route = new Routes();
			int idUser = user.getIdU();
			BeanUtilities.populateBean(route, request.getParameterMap());
			route.setIdU(idUser);
		    HibernateUtil<Routes> hu = new HibernateUtil<Routes>();
	
		    try{
		    	hu.create(route);
		    	response.sendRedirect("/runWithJava/user_route.jsp");
		    } catch(Exception e) {
			      session.setAttribute("error", e.getMessage());
			      session.setAttribute("errorObject", user);
			      response.sendRedirect("/runWithJava/user_route.jsp");
		    }
		}
	}

}
